Using :nth-child() and :nth-of-type() for Odd and Even Elements
CSS pseudo-classes :nth-child() and :nth-of-type() allow you to select elements based on their position. You can use them to target every odd or even element efficiently.
:nth-child(even) – Selects every even child of its parent (2nd, 4th, 6th, etc.).
:nth-child(odd) – Selects every odd child of its parent (1st, 3rd, 5th, etc.).
:nth-of-type(even) – Selects every even element of the specified type among siblings.
:nth-of-type(odd) – Selects every odd element of the specified type among siblings.
In this example, :nth-child(even) and :nth-child(odd) alternate the background color of all list items, while :nth-of-type(even) makes every even <li> bold, ignoring other sibling element types.
Use :nth-child() when you want to style elements based on their absolute position among all children.
Use :nth-of-type() when styling elements of a specific type among siblings.
Combine odd/even pseudo-classes with other selectors for more precise styling.
Test in complex HTML structures to ensure the desired elements are targeted correctly.
You're building a pricing table with alternating background colors — how would you select every odd row using CSS?
A list of user comments has inconsistent styling on even items — what CSS rule would you write to fix it, and why might it not work if the HTML structure changes?
Our product grid is supposed to highlight every even card, but after adding a filter that hides some items, the pattern is broken — what’s happening, and how do you fix it without changing the HTML?
A designer wants every third item in a dynamic feed to have a special border, but the team is using a library that injects placeholder elements — how would you debug and solve this without touching the library code?
You're designing a responsive component library where odd/even styling is used for accessibility contrast, but screen readers and dynamic content reordering break the visual pattern — how do you ensure semantic and visual consistency across devices and assistive tech?
In a large-scale CMS, authors can insert arbitrary content blocks that break the nth-child pattern — how would you architect a robust CSS strategy that survives unpredictable DOM structures without relying on JS?
We're migrating a legacy UI from inline styles and JS-based alternation to pure CSS — how do you prioritize which components to refactor first, and how do you measure the impact on performance and accessibility across 50+ product pages?
A cross-team component system uses odd/even styling inconsistently across 12 micro-frontends — how do you enforce standardization without breaking existing layouts, and what metrics would you track to validate success?